#!/bin/bash
# 备份数据库
# crontab 30 3 * * * source $HOME/.bash_profile && sh /sumz/script/mongo_bak.sh >> /sumz/mysql_bak.log 2>&1
# 定义备份目录
bakurl="/sumz/data_bak/mongo_bak_file/"

# 定义需要备份的项目名
projects=("alarm_db" "spectrumer_db")

# 计算项目数量
num_projects=${#projects[@]}

# 获取当前星期几
ntime=$(date -d "$(date +%Y-%m-%d)" +%w)

dtime=$(date +'%Y%m%d-%H%M%S')

# 备份函数
backup_project() {
    project_name=$1
    mkdir -p "$bakurl/$project_name"

    bak_name=$project_name-$dtime

    /usr/local/bin/kubectl exec mongo-v1-0 -n base -ti -- mongodump -d $project_name  -u root -p Sumz --port 27017 --authenticationDatabase admin -o /tmp/$bak_name

    /usr/local/bin/kubectl cp mongo-v1-0:/tmp/$bak_name $bakurl/$project_name/$bak_name -n base
    
    cd "$bakurl$project_name" &&  zip -r $bak_name.zip $bak_name
    
    rm -r $bak_name
    /usr/local/bin/kubectl exec mongo-v1-0 -n base -ti -- rm -r /tmp/$bak_name
}

# 删除一个月以前的文件（除星期五以外）
delete_old_files() {
    project_name=$1
    # 计算一个月前的时间戳
    rtime=$(date -d "$(date +%Y-%m-%d -d '-30 day')" +%s)
    cd "$bakurl/$project_name"
    for filename in $(ls "$bakurl/$project_name")
    do
        fntime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%w)
        baktime=$(date -d $(ls --full-time $filename | awk {'print $6'}) +%s)
        if [ $rtime -gt $baktime ] && [ $fntime -ne 5 ]
        then
            rm -f "$bakurl/$project_name/$filename"
        fi
    done
}

# 备份和删除文件
for ((i=num_projects-1; i>=0; i--))
do
    backup_project "${projects[$i]}"
    delete_old_files "${projects[$i]}"
done
